package com.tanhua.server.service;

import com.tanhua.autoconfig.template.AipFaceTemplate;
import com.tanhua.autoconfig.template.OssTemplate;
import com.tanhua.dubbo.api.RecommendUserApi;
import com.tanhua.dubbo.api.UserInfoApi;
import com.tanhua.dubbo.api.UserLikeApi;
import com.tanhua.dubbo.api.VisitorsApi;
import com.tanhua.model.domain.UserInfo;
import com.tanhua.model.mongo.RecommendUser;
import com.tanhua.model.mongo.UserLike;
import com.tanhua.model.mongo.Visitors;
import com.tanhua.model.vo.ErrorResult;
import com.tanhua.model.vo.PageResult;
import com.tanhua.model.vo.UserInfoVo;
import com.tanhua.server.exception.BusinessException;
import com.tanhua.server.interceptor.UserHolder;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
public class UserInfoService {

    @Autowired
    private UserService userService;

    @DubboReference
    private UserInfoApi userInfoApi;

    @DubboReference
    private UserLikeApi userLikeApi;

    @DubboReference
    private VisitorsApi visitorsApi;

    @DubboReference
    private RecommendUserApi recommendUserApi;

    @Autowired
    private OssTemplate ossTemplate;

    @Autowired
    private AipFaceTemplate aipFaceTemplate;

    @Autowired
    private TanhuaService tanhuaService;

    @Autowired
    private UserInfoService userInfoService;

    public void save(UserInfo userInfo) {
        userInfoApi.save(userInfo);
    }

    //更新用户头像
    public void updateHead(MultipartFile headPhoto, Long id) throws IOException {
        //1、将图片上传到阿里云oss
        String imageUrl = ossTemplate.upload(headPhoto.getOriginalFilename(), headPhoto.getInputStream());
        //2、调用百度云判断是否包含人脸
        boolean detect = aipFaceTemplate.detect(imageUrl);
        //2.1 如果不包含人脸，抛出异常
        if (!detect) {
            throw new BusinessException(ErrorResult.faceError());
        } else {
            //2.2 包含人脸，调用API更新
            UserInfo userInfo = new UserInfo();
            userInfo.setId(id);
            userInfo.setAvatar(imageUrl);
            userInfoApi.update(userInfo);

        }
    }

    //根据id查寻
    public UserInfoVo findById(Long id) {
        UserInfo userInfo = userInfoApi.findById(id);

        UserInfoVo vo = new UserInfoVo();

        BeanUtils.copyProperties(userInfo, vo); //copy同名同类型的属性

        if (userInfo.getAge() != null) {
            vo.setAge(userInfo.getAge().toString());
        }


        return vo;
    }

    //更新
    public void update(UserInfo userInfo) {
        userInfoApi.update(userInfo);

    }


    /*
    互相喜欢，喜欢，粉丝 - 统计
     */
    public Map counts(Map count) {

        Long userId = UserHolder.getUserId();

        count = userLikeApi.counts(userId, count);

        return count;

    }


    /*
互相喜欢，粉丝，关注，谁看过我
*/
    public PageResult findOther(String type, int page, int pageSize, String nickName) {
        //获取当前id
        Long userId = UserHolder.getUserId();
        PageResult pageResult = new PageResult();
        //判断type查谁
        switch (type) {
            case "1":
                //1 互相关注
                pageResult = extracted(page, pageSize, userId, nickName);
                break;
            case "2":
                //2 喜欢
                pageResult = like(page, pageSize, userId, nickName);
                break;
            case "3":
                //3 粉丝（喜欢我）
                pageResult = likeMe(page, pageSize, userId, nickName);
                break;
            case "4":
                //4 谁看过我
                pageResult = queryMyVisitors(page, pageSize, userId);
                break;
            default:
                new BusinessException(ErrorResult.error());
        }
        return pageResult;
    }

    /*
 是否喜欢
  */
    public Boolean alreadyLove(Long userId, Long likeUserId) {
        //api查询是否喜欢
        UserLike like = userLikeApi.whetherLike(userId, likeUserId);

        if (like != null) {
            return true;
        }
        return false;
    }

    /*
    互相喜欢
     */
    private PageResult extracted(int page, int pageSize, Long userId, String nickName) {
        //查询数据
        List<UserLike> findOther = userLikeApi.otherLike(userId);

        //封装vo对象
        List<UserInfoVo> vos = new ArrayList<>();
        for (UserLike userLike : findOther) {
            UserInfoVo userInfoVo = new UserInfoVo();
            Long UserId = userLike.getUserId();
            UserInfo userInfo = userInfoApi.findByIdOrName(UserId, nickName);
            //封装Vos对象
            BeanUtils.copyProperties(userInfo, userInfoVo);
            RecommendUser recommendUser = recommendUserApi.queryByUserId(userLike.getLikeUserId(), userId);
            int value = recommendUser.getScore().intValue();
            userInfoVo.setMatchRate(value);
            userInfoVo.setAlreadyLove(userInfoService.alreadyLove(userId, userLike.getLikeUserId()));
            vos.add(userInfoVo);
        }
        PageResult pageResult = new PageResult(page, pageSize, Long.valueOf(vos.size()), vos);
        return pageResult;
    }

    /*
    粉丝
     */
    private PageResult likeMe(int page, int pageSize, Long userId, String nickName) {
        //查询数据
        List<UserLike> findOther = userLikeApi.likeMe(userId);
        //封装vo对象
        List<UserInfoVo> vos = new ArrayList<>();
        for (UserLike userLike : findOther) {
            UserInfoVo userInfoVo = new UserInfoVo();
            Long UserId = userLike.getUserId();
            UserInfo userInfo = userInfoApi.findByIdOrName(UserId, nickName);
            //封装Vos对象
            BeanUtils.copyProperties(userInfo, userInfoVo);
            RecommendUser recommendUser = recommendUserApi.queryByUserId(userLike.getLikeUserId(), userId);
            int value = recommendUser.getScore().intValue();
            userInfoVo.setMatchRate(value);
            userInfoVo.setAlreadyLove(userInfoService.alreadyLove(userId, userLike.getLikeUserId()));
            vos.add(userInfoVo);
        }
        PageResult pageResult = new PageResult(page, pageSize, Long.valueOf(vos.size()), vos);
        return pageResult;

    }


    /*
    谁看过我
     */
    private PageResult queryMyVisitors(int page, int pageSize, Long userId) {
        List<Visitors> visitors = visitorsApi.queryMyVisitors(null, userId);
        //封装vo对象
        List<UserInfoVo> vos = new ArrayList<>();
        for (Visitors visitor : visitors) {
            UserInfoVo userInfoVo = new UserInfoVo();
            Long UserId = visitor.getUserId();
            UserInfo userInfo = userInfoApi.findById(visitor.getVisitorUserId());
            //封装Vos对象
            BeanUtils.copyProperties(userInfo, userInfoVo);
            RecommendUser recommendUser = recommendUserApi.queryByUserId(visitor.getVisitorUserId(), visitor.getUserId());
            int value = recommendUser.getScore().intValue();
            userInfoVo.setMatchRate(value);
            userInfoVo.setAlreadyLove(userInfoService.alreadyLove(userId, visitor.getVisitorUserId()));
            vos.add(userInfoVo);
        }
        PageResult pageResult = new PageResult(page, pageSize, Long.valueOf(vos.size()), vos);
        return pageResult;
    }

    /*
    喜欢
     */
    private PageResult like(int page, int pageSize, Long userId, String nickName) {
        List<UserLike> list = userLikeApi.like(userId);
        //封装vo
        ArrayList<UserInfoVo> vos = new ArrayList<>();
        for (UserLike userLike : list) {
            //获取信息 拷贝到vo对象
            UserInfoVo userInfoVo = new UserInfoVo();
            //获取符合条件的当前用户id  api查询信息
            Long userId1 = userLike.getLikeUserId();
            UserInfo userInfo = userInfoApi.findByIdOrName(userId1, nickName);
            //拷贝
            BeanUtils.copyProperties(userInfo, userInfoVo);
            //添加vo对象没有的属性
            RecommendUser recommendUser = recommendUserApi.queryByUserId(userLike.getLikeUserId(), userId);
            int value = recommendUser.getScore().intValue();
            userInfoVo.setMatchRate(value);
            userInfoVo.setAlreadyLove(userInfoService.alreadyLove(userId, userLike.getLikeUserId()));
            vos.add(userInfoVo);
        }
        PageResult pageResult = new PageResult(page, pageSize, Long.valueOf(vos.size()), vos);
        return pageResult;
    }

    /*
    粉丝喜欢
     */
    public void fansLike(Long fansUserId) {
        Long userId = UserHolder.getUserId();
        //api判断条件
        userLikeApi.fansLike(userId, fansUserId);
    }

    /*
    取消喜欢
     */
    public void notLike(Long likeUserId) {
        Long userId = UserHolder.getUserId();
        userLikeApi.notLike(userId, likeUserId);

    }


}

